import os
from OFS.Folder import Folder
from permissions import View
from AccessControl.SecurityInfo import ClassSecurityInfo
from zuite import manage_addZuite
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from Products.CMFCore.DirectoryView import manage_addDirectoryView, registerDirectory



try:
    from Products.GenericSetup.interfaces import IImportContext
    from Products.PluggableAuthService.exportimport import importPAS
    from Products.PluggableAuthService.PluggableAuthService import \
         addPluggableAuthService
    HAS_GENERICSETUP = True
except ImportError:
    from AccessControl.User import manage_addUserFolder
    from Products.CMFCore.CookieCrumbler import manage_addCC
    HAS_GENERICSETUP = False

from zope.interface import implements


WWW = os.path.join(os.path.dirname(__file__), 'www')
PAS_PROFILE = os.path.join(os.path.dirname(__file__), 'profiles', 'pas')

class Zelenium(Folder):
    meta_type = 'Zelenium Workspace'

    security = ClassSecurityInfo()
    security.declareObjectProtected( View )

    if HAS_GENERICSETUP:
        security.declareProtected(View, 'login_form' )
        def login_form(self, REQUEST):
            """Present login form.
            """
            return self.acl_users.cookies.login_form(REQUEST)
    else:
        security.declareProtected(View, 'login_form' )
        login_form = PageTemplateFile('login_form', WWW)

        security.declareProtected(View, 'login' )
        login = PageTemplateFile( 'login', WWW )


    security.declarePublic('logout')
    def logout(self, REQUEST):
        """Logs out the user and redirects to the logout page.
        """
        if HAS_GENERICSETUP:
            # Strip the request referrer so that logout is well
            # behaved within selenium.
            REQUEST['HTTP_REFERER'] = None
            self.acl_users.logout(REQUEST)
            return "Logged out."
        else:
            return self.cookie_crumbler.logout()


manage_addZeleniumForm = PageTemplateFile('addZelenium', WWW)


def manage_addZelenium(dispatcher, id='zelenium', title='', tests_path='',
                       REQUEST=None):
    """Add a new Zelenium testing area to dispatcher's objects.
    """
    zelenium = Zelenium(id)
    dispatcher._setObject(id, zelenium)
    zelenium = dispatcher._getOb(id)
    if HAS_GENERICSETUP:
        addPluggableAuthService(zelenium)
        pas = zelenium._getOb('acl_users')
        importPAS(ImportContext(pas))
        # shouldn't have to do the following
        pas.userFolderAddUser('manager', 'manager', ['Manager'], [])
    else:
        manage_addUserFolder(zelenium)
        zelenium.acl_users.userFolderAddUser('manager', 'manager', ['Manager'],
                                             [])
        manage_addCC(zelenium, 'cookie_crumbler')
    manage_addZuite(zelenium, 'zuite')

    # products modules can come from many places
    tests_path_pieces = tests_path.split('/')
    product_name = tests_path_pieces[0]
    tests_sub_path = os.path.sep.join(tests_path_pieces[1:])
    import Products
    try:
        product_module = getattr(Products, product_name)
        tests_path = os.path.join(os.path.dirname(product_module.__file__),
                                  tests_sub_path)
    except:
        #try a dotted module name
        try:
            exec('import %s as testmodule' %(tests_path))
            tests_path = os.path.dirname(testmodule.__file__)
        except:
            raise ValueError(
                "Can not find referenced module by path or dotted name")

    assert os.path.exists(tests_path), 'Path does not exist: %s' % tests_path
    zelenium.zuite.manage_changeProperties({'filesystem_path': tests_path})

    # add in a content folder if it exists in the tests_path
    content_folder_fullpath = os.path.join( tests_path, 'content' )
    content_folder = content_folder_fullpath[content_folder_fullpath.find(
        'Products')+len('Products/'):]
    if os.path.exists(content_folder_fullpath):
        manage_addDirectoryView(zelenium,
                                content_folder,
                                'content')
    if REQUEST is not None:
        REQUEST['RESPONSE'].redirect('%s/manage_main'
                                     '?manage_tabs_message='
                                     'Zelenium+workspace+added.'
                                     % dispatcher.absolute_url())

if HAS_GENERICSETUP:

    class ImportContext:
        """ImportContext for importing a pre-configured PAS.
        """

        implements(IImportContext)

        def __init__(self, site):
            self._site = site
            self._tool = None
            self._purge = True
            self._encoding = None
            self._notes = []
            self._base_path = PAS_PROFILE

        def getSite(self):
            return self._site

        def getSetupTool(self):
            return self._tool

        def getEncoding(self):
            return self._encoding

        def getLogger(self, name):
            return DummyLogger(name, self._notes)

        def readDataFile(self, filename, subdir=None):
            if subdir is None:
                path = os.path.join(self._base_path, filename)
            else:
                path = os.path.join(self._base_path, subdir, filename)
            if os.path.exists(path):
                return open(path).read()
            else:
                return None

        def shouldPurge( self ):
            return self._purge
